package common.page;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * 兼容前端分页
 * 后端分页从第0页开始,前端从第1页开始,此处做一个转换
 * Created by zhuxh on 16/7/29.
 */
public class ViewPage<T> implements Page<T> {

    private final long totalElements;

    private final long totalPages;

    private final Pageable pageable;

    private final List<T> content = new ArrayList<T>();

    public ViewPage(List<T> content, Pageable pageable, long total) {
        this.totalElements = total;
        this.content.addAll(content);
        this.pageable = pageable;
        int size = pageable.getPageSize();
        this.totalPages = total % size == 0 ? total / size : total / size + 1;

    }

    public ViewPage(Page page, Pageable pageable) {
        this(page.getContent(), pageable, page.getTotalElements());
    }

    @Override
    public int getTotalPages() {
        return (int) totalPages;
    }

    @Override
    public long getTotalElements() {
        return totalElements;
    }

    @Override
    public int getNumber() {
        return pageable.getPageNumber();
    }

    @Override
    public int getSize() {
        return pageable.getPageSize();
    }

    @Override
    public int getNumberOfElements() {
        return content.size();
    }

    @Override
    public List<T> getContent() {
        return content;
    }

    @Override
    public boolean hasContent() {
        return content.size() > 0;
    }

    @Override
    public Sort getSort() {
        return pageable.getSort();
    }

    @Override
    public boolean isFirst() {
        return pageable.getPageNumber() == 1;
    }

    @Override
    public boolean isLast() {
        return pageable.getPageNumber() == totalPages;
    }

    @Override
    public boolean hasNext() {
        return pageable.getPageNumber() < totalPages;
    }

    @Override
    public boolean hasPrevious() {
        return pageable.getPageNumber() > 0;
    }

    @Override
    public Pageable nextPageable() {
        return null;
    }

    @Override
    public Pageable previousPageable() {
        return null;
    }

    @Override
    public <S> Page<S> map(Converter<? super T, ? extends S> converter) {
        return null;
    }

    @Override
    public Iterator<T> iterator() {
        return content.iterator();
    }
}
